package com.ld.collegetask;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.view.View;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.ld.collegetask.beans.BaseJsonBean;
import com.ld.collegetask.databinding.ActivityOrderMemberReleaseBinding;
import com.ld.collegetask.serverInterface.RequestSerives;
import com.ld.collegetask.utils.AppApplication;
import com.ld.collegetask.utils.CurrencyUtils;
import com.ld.collegetask.utils.SharePreference;
import com.ld.collegetask.utils.ToastUtil;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import me.leefeng.promptlibrary.PromptDialog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class OrderMemberReleaseActivity extends BaseActivity {
    private String tag = "OrderMemberReleaseActivity";

    private static final int CLASS = 1000;
    private static final int ENDADDRESS = 1001;
    private static final int TIME = 1002;
    private static final int COUPON = 1003;
    private static final int OCOST = 1004;
    private static final int SEX = 1005;
    private PromptDialog promptDialog;

    private Integer userId = 0;

    private ActivityOrderMemberReleaseBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_order_member_release);
        //设置标题
        setTitleView(this, binding.ilTitle, true, true, false,false);
        setLoadingView(this,binding.ilLoading);
        setTitle("发布");
        /**
         * 获取用户全局变量
         * **/
        SharePreference sp = new SharePreference(getBaseContext());
        userId = sp.getUserId();

        promptDialog = new PromptDialog(this);
        binding.orderMemberReleaseSexOnck.setText(sexName);

        binding.rlOrderMemberReleaseClass.setOnClickListener(this);
        binding.rlOrderMemberReleaseCoupon.setOnClickListener(this);
        binding.rlOrderMemberReleaseEndaddress.setOnClickListener(this);
        binding.rlOrderMemberReleaseTime.setOnClickListener(this);
        binding.orderMemberReleaseButton.setOnClickListener(this);
        binding.rlOrderMemberReleaseOcost.setOnClickListener(this);
        binding.rlOrderMemberReleaseSex.setOnClickListener(this);
    }

    @Override
    public void loading() {

    }

    private void order_member_save(Integer userId, Integer genderlimit, Integer orderclassId, Integer discountreleaseId, String endaddress, String realname, String ophone, String oremark, String ocost, String ocommission, String olife) {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<String> call = requestSerives.order_member_save(userId, genderlimit, orderclassId, discountreleaseId,
                endaddress, realname, ophone, oremark, ocost, ocommission, olife);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(response.body().toString(), BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    promptDialog.dismiss();
                    Intent it = new Intent(OrderMemberReleaseActivity.this, MainActivity.class);
                    setResult(1, it);
                    finish();
                } else {
                    promptDialog.showWarn(base.getMsg());
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                ToastUtil.showLong(OrderMemberReleaseActivity.this, "网络错误，请检查网络");
                promptDialog.dismiss();
            }
        });
    }

    private Integer orderclassId;
    private String orderclassName;
    private Integer addressId;
    private String address;
    private String dname;
    private String discount = "0";
    private String dbegindate;
    private String denddate;
    private String dcreatedate;
    private String realname;
    private String ophone;
    private String oremark;
    private String olife;
    private String ocost = "0";
    private String ocommission = "0";
    private Integer discountId = 0;
    private String prepay = "0";
    private Integer dstatus = 0;
    private Integer genderlimit = 0;
    private Integer discountreleaseId = 0;
    private Integer sex = 3;
    private String sexName = "不限制";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CLASS:
                if (resultCode == 1) {
                    orderclassId = data.getIntExtra("orderclassId", 0);
                    orderclassName = data.getStringExtra("orderclassName");
                    binding.orderMemberReleaseClassOnck.setText(orderclassName);
                }
                break;
            case ENDADDRESS:
                if (resultCode == 1) {
                    addressId = data.getIntExtra("addressId", 0);
                    address = data.getStringExtra("address");
                    binding.orderMemberReleaseEndaddressOnck.setText(address);
                }
                break;
            case TIME:
                break;
            case COUPON:
                if (resultCode == 1) {
                    prepay = CurrencyUtils.add(prepay,discount);
                    dname = data.getStringExtra("orderclassDname");
                    discount = data.getStringExtra("orderclassDiscount");
                    dbegindate = data.getStringExtra("orderclassDbegindate");
                    dcreatedate = data.getStringExtra("orderclassDcreatedate");
                    dstatus = data.getIntExtra("orderclassDstatus", 0);
                    discountId = data.getIntExtra("orderclassDiscountId", 0);
                    binding.orderMemberReleaseCouponOnck.setText("已优惠 " + Integer.valueOf(discount) + " 元");
                    prepay = CurrencyUtils.subtract(prepay,discount);
                    if (CurrencyUtils.compareTo(prepay,"0")==-1){
                        prepay = "0";
                    }
                    binding.orderMemberReleaseMoney.setText("¥" + prepay + "元");
                }
                break;
            case OCOST:
                if (resultCode == 1) {
                    prepay = CurrencyUtils.subtract(prepay,ocost,ocommission);
                    if (!CurrencyUtils.add(ocost,ocommission).equals(
                            CurrencyUtils.add(data.getStringExtra("ocost"),data.getStringExtra("ocommission")))) {
                        prepay = CurrencyUtils.add(prepay,discount);
                        discount = "0";
                        discountId = 0;
                        binding.orderMemberReleaseCouponOnck.setText("");
                        binding.orderMemberReleaseCouponOnck.setHint("请选择");
                    }
                    ocost = data.getStringExtra("ocost");
                    ocommission = data.getStringExtra("ocommission");
                    binding.orderMemberReleaseOcostOnck.setText((Float.valueOf(ocost) + "+" + Float.valueOf(ocommission)) + " 元");
                    prepay = CurrencyUtils.add(prepay,ocost,ocommission);
                    binding.orderMemberReleaseMoney.setText("¥" + prepay + "元");
                }
                break;
            case SEX:
                if (resultCode == 1) {
                    sex = data.getIntExtra("sexId", 3);
                    sexName = data.getStringExtra("sexName");
                    binding.orderMemberReleaseSexOnck.setText(sexName);
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.rl_order_member_release_class:                    //跳转到任务类型
                startActivityForResult(new Intent(this, OrderMemberReleaseClassListActivity.class), CLASS);
                break;
            case R.id.rl_order_member_release_endaddress:               //跳转到结束地址
                startActivityForResult(new Intent(this, OrderMemberReleaseAddressListActivity.class), ENDADDRESS);
                break;
            case R.id.rl_order_member_release_time:                     //跳转到任务时间
                hideSoftKeyboard();
                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                endDate.add(Calendar.MONTH, 1);
                //时间选择器
                TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        denddate = getTime(date);
                        binding.orderMemberReleaseTimeOnck.setText(denddate);
                    }
                })
                        .setType(new boolean[]{true, true, true, true, true, false})// 默认全部显示
                        .setRangDate(startDate, endDate)//起始终止年月日设定
                        .build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
                break;
            case R.id.rl_order_member_release_coupon:                      //跳转到优惠卷
                startActivityForResult(new Intent(this, OrderMemberReleaseDiscountListActivity.class).putExtra("ocommission", ocommission), COUPON);
                break;
            case R.id.order_member_release_button:                      //提交按钮
                realname = binding.orderMemberReleaseRealnameShuru.getText().toString();
                ophone = binding.orderMemberReleaseOphoneShuru.getText().toString();
                oremark = binding.orderMemberReleaseOremark.getText().toString();
                olife = binding.orderMemberReleaseTimeOnck.getText().toString();
                if (orderclassName == null) {
                    promptDialog.showWarn("请选择任务类型");
                    return;
                }
                if (address == null) {
                    promptDialog.showWarn("请选择地址");
                    return;
                }
                if (denddate == null) {
                    promptDialog.showWarn("请选择时间");
                    return;
                }
                if (realname.equals("")) {
                    promptDialog.showWarn("请输入联系人");
                    return;
                }
                if (ophone.equals("")) {
                    promptDialog.showWarn("请输入电话");
                    return;
                }
                if (CurrencyUtils.add(ocost,ocommission).equals("0")) {
                    promptDialog.showWarn("请输入费用");
                    return;
                }
                promptDialog.showLoading("正在提交");
                order_member_save(userId, sex, orderclassId, discountId, address, realname, ophone, oremark, ocost, ocommission, denddate);
                break;
            case R.id.rl_order_member_release_ocost:                //跳转到跑腿金额
                startActivityForResult(new Intent(this, OrderMemberReleaseOcostListActivity.class).putExtra("ocost", ocost).putExtra("ocommission", ocommission), OCOST);
                break;
            case R.id.rl_order_member_release_sex:
                startActivityForResult(new Intent(this, OrderMemberReleaseSexListActivity.class), SEX);
                break;
        }
    }

    /**
     * 获取现在时间
     *
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String getTime(Date currentTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }
}
